package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public EmployeeLoginVO login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //登录成功了，就生成token。
        String token = JwtUtil.getToken(employee.getId());

        //封装VO对象
        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();
        BeanUtils.copyProperties(employee, employeeLoginVO);
        employeeLoginVO.setToken(token);

        System.out.println(employeeLoginVO);



        //3、返回实体对象
        return employeeLoginVO;
    }



    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO) {

        //非空判断
        if(employeePageQueryDTO == null ){
            return Result.error("分页查询失败...");
        }

        //开启分页
        PageHelper.startPage(employeePageQueryDTO.getPage() , employeePageQueryDTO.getPageSize());

        //调用mapper
        Page page = employeeMapper.pageQueryEmp(employeePageQueryDTO);

        //封装，并返回值
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());

        return Result.success(pageResult);
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public Result addEmp(EmployeeDTO employeeDTO) {
        //非空判断
        if(employeeDTO == null){
            return Result.error("新增员工失败...");
        }

        //信息不全
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        employee.setStatus(StatusConstant.ENABLE);

        /*
            需要获得更新人的信息，即当前登录用户的信息，就需要去线程拿
                解决办法，在拦截器那里，通过token解析，得到当前登录用户的id，
                放到BaseContext中，
         */
        Long loginId = BaseContext.getCurrentId();

        //调用mapper
        employeeMapper.addEmp(employee);

        //返回数据
        return Result.success();
    }

    /**
     * 改变员工状态
     *
     * @param status
     * @param id
     * @return
     */
    @Override
    public Result changeEmpStatus(Integer status, Long id) {
        //边界判断
        if(status == null || id == null){
            return Result.error("信息错误");
        }
        //补全信息
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);

        Long LoginID = BaseContext.getCurrentId();
        employee.setUpdateUser(LoginID);
        employee.setUpdateTime(LocalDateTime.now());

        //调用mapper
        employeeMapper.updateEmp(employee);

        //返回值
        return Result.success();
    }

    /**
     * 根据ID查询，回显员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Result<Employee> getByID(Long id) {
        //边界判断
        if(id == null){
            return Result.error("根据员工ID查询失败");
        }
        //调用mapper
        Employee employee = employeeMapper.getByUserId(id);
        //返回数据
        return Result.success(employee);
    }

    /**
     * 修改员工信息
     *
     * @param employeeDTO
     * @return
     */
    @Override
    public Result updateEmp(EmployeeDTO employeeDTO) {
        //边界判断
        if(employeeDTO == null){
            return Result.error("更新员工信息失败...");
        }
        //补全信息
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        employee.setUpdateTime(LocalDateTime.now());

        Long loginID = BaseContext.getCurrentId();
        employee.setUpdateUser(loginID);

        //调用mapper
        employeeMapper.updateEmp(employee);

        //返回数据
        return Result.success();
    }

}
